/*
 * Description: 数组相关的工具方法
 * Author: wangyifei
 * DateCreated: 2024-04-03 17:55
 */

/**
 * 数组转树型结构
 * @param list 数据源
 * @param id id字段名 默认 'id'
 * @param parentId 父节点字段名 默认 'pid'
 * @param children 子节点字段名 默认 'children'
 */
export function handleTree(list: any[], id?: string, parentId?: string, children?: string) {
	const config = {
		id: id || 'id',
		parentId: parentId || 'pid',
		childrenList: children || 'children'
	};

	const childrenListMap = {};
	const nodeIds = {};
	const tree = [];

	for (const item of list) {
		const parentId = item[config.parentId];
		if (!childrenListMap[parentId]) {
			childrenListMap[parentId] = [];
		}
		nodeIds[item[config.id]] = item;
		childrenListMap[parentId].push(item);
	}

	for (const item of list) {
		const parentId = item[config.parentId];
		if (!nodeIds[parentId]) {
			tree.push(item);
		}
	}

	function adaptToChildrenList(item: any) {
		if (childrenListMap[item[config.id]]) {
			item[config.childrenList] = childrenListMap[item[config.id]];
		}
		if (item[config.childrenList]) {
			for (const cc of item[config.childrenList]) {
				adaptToChildrenList(cc);
			}
		}
	}
	for (const item of tree) {
		adaptToChildrenList(item);
	}

	return tree;
}
